package com.qingzhuge.context;

import cn.hutool.crypto.SecureUtil;
import com.qingzhuge.autoconfigure.QingTingProperties;
import com.qingzhuge.common.Constants;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author : zero.xiao
 * @description : 获取系统配置属性
 * @date :2019-05-21 09:18
 * @modified :
 */
public class PropertyPlaceholder  extends PropertyPlaceholderConfigurer implements ApplicationContextAware {

    private ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    protected void loadProperties(@NonNull Properties props) throws IOException {
        super.loadProperties(props);
        QingTingProperties qingTingProperties = applicationContext.getBean(QingTingProperties.class);
        List<String> decryptProperties = qingTingProperties.getDecryptProperties();
        for (Map.Entry<Object, Object> entry : props.entrySet()) {
            String keyStr = entry.getKey().toString();
            String value = entry.getValue().toString();
            if (decryptProperties != null && decryptProperties.contains(keyStr)) {
                String dbKey = Constants.DB_KEY;
                byte[] decrypt = SecureUtil.des(dbKey.getBytes()).decrypt(value);
                value = new String(decrypt);
                props.setProperty(keyStr, value);
            }
            PropertiesContext.getProperties().put(keyStr, value);
        }
    }
}
